# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from django.db.models.signals import post_save


class UserSignatureType(models.Model):
    """
    The appearance of user's signature
    
    The 'signature' field value must be a combination of field names of User or/and UserProfile
    fields, separated by +. For a short entry in the form of a capital letter, use the prefix
    short#. For example: value 'short#first_name+short#patronymic+last_name' for John Fitzgerald
    Kennedy means 'J. F. Kennedy' signature.
    """
    title = models.CharField(_('title'), max_length=50)
    signature = models.CharField(_('signature'), max_length=50)

    class Meta:
        verbose_name = _('user signature type')
        verbose_name_plural = _('user signature types')

    def __unicode__(self):
        return self.title


class UserProfile(models.Model):
    """
    User additional information
    """
    GENDER_CHOISES = (('x', _('no')), ('m', _('male')),('f', _('female')))
    
    user = models.OneToOneField(User)
    
    patronymic = models.CharField(_('patronymic'), max_length=30, blank=True)
    nick_name = models.CharField(_('nick name'), max_length=30, blank=True)
    birthday = models.DateField(_('birthday'), blank=True, null=True)
    gender = models.CharField(_('gender'), max_length=1, choices=GENDER_CHOISES, default='x')
    avatar = models.ImageField(_('avatar'), blank=True, null=True, upload_to='static/userpic')
    signature_type = models.ForeignKey(UserSignatureType, verbose_name=_('signature type'),
                                       blank=True, null=True)

    class Meta:
        verbose_name = _('user profile')
        verbose_name_plural = _('user profiles')

    def __unicode__(self):
        return self.user.username


def create_user_profile(sender, instance, created, **kwargs):
    """
    post_save User handler, automatically creating UserProfile for new User
    """
    if created:
        UserProfile.objects.create(user=instance)


# Connect handler for User's post_save signal
post_save.connect(receiver=create_user_profile, sender=User)
